package com.xiaoyu.im.provider;

import android.text.TextUtils;

import com.xiaoyu.base.entity.ConversationEntity;
import com.xiaoyu.im.client.IMClient;
import com.xiaoyu.im.datamodel.vendors.NimConversationUnique;
import com.xiaoyu.im.datamodel.vendors.VendorConversationUnique;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatIdMapper {

    private static final String TAG = "ChatIdMapper";
    private static final ChatIdMapper INSTANCE = new ChatIdMapper();

    private final Map<String, String> mUidMap = new ConcurrentHashMap<>();
    private final Map<VendorConversationUnique, String> mVendorMap = new ConcurrentHashMap<>();

    public static ChatIdMapper getInstance() {
        return INSTANCE;
    }

    private ChatIdMapper() {
    }

    void update(ConversationEntity entity) {
        final String chatId = entity.getChatId();
        if (TextUtils.isEmpty(chatId)) {
            return;
        }
        final String uid = entity.getToUid();
        if (!TextUtils.isEmpty(uid)) {
            mUidMap.put(uid, chatId);
        }

        final VendorConversationUnique unique = IMClient.getInstance().getConversationUnique(chatId);
        if (unique != null) {
            mVendorMap.put(unique, chatId);
        }
    }

    void delete(String chatId) {
        if (TextUtils.isEmpty(chatId)) {
            return;
        }
        for (Map.Entry<String, String> entry : mUidMap.entrySet()) {
            if (TextUtils.equals(entry.getValue(), chatId)) {
                mUidMap.remove(entry.getKey());
                break;
            }
        }

        for (Map.Entry<VendorConversationUnique, String> entry : mVendorMap.entrySet()) {
            if (TextUtils.equals(entry.getValue(), chatId)) {
                mVendorMap.remove(entry.getKey());
                break;
            }
        }
    }

    public String getChatIdByUid(String uid) {
        return mUidMap.get(uid);
    }

    public String getChatIdByVendor(VendorConversationUnique unique) {
        return mVendorMap.get(unique);
    }

    public String getUid(String chatId) {
        ConversationEntity conversation = ConversationManager.getInstance().fetchConversation(chatId);
        return conversation != null ? conversation.getToUid() : null;
    }

    public void clear() {
        mUidMap.clear();
        mVendorMap.clear();
    }
}
